<?php

$keep_time = 30; // 存活时间

$thrift_servers = array();
$serv = new swoole_server("127.0.0.1", 8081);
$serv->set(array(
//    'worker_num' => 8,   //工作进程数量
//    'daemonize' => true, //是否作为守护进程
    'open_eof_check' => true,
    'package_eof' => "\r\n"
));
$serv->on('connect', function ($serv, $fd){
    echo "Client:Connect.\r\n";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    $fdinfo = $serv->connection_info($fd);
    $remote_ip = $fdinfo["remote_ip"];
    $remote_port = $fdinfo["remote_port"];

    echo "on receive:".$data."\n";
    global $thrift_servers;
    global $keep_time;
    $data = json_decode($data, true);
    if(empty($data) == false){
        $clentKey = $remote_ip.':'.$remote_port;
        $nowtime = time();
        $data['time'] = $nowtime;
        $thrift_servers[$clentKey] = $data;
        $activeServers = array();
        foreach($thrift_servers as $key => $server){
            if(($nowtime - $server['time']) < $keep_time){
//                 $activeServers[] = $server;
                $activeServers[] = array('host'=>$server['host'],'port'=>$server['port']);
            }
            else{
                unset($thrift_servers[$key]);
            }
        }
        if(count($activeServers) > 0){
            $sendData = json_encode($activeServers);
            echo "send to $clentKey:" . $sendData."\n";
            $serv->send($fd, $sendData."\r\n");
        }
    }
    else{
        echo "on receive data format error\n";
    }
});
$serv->on('close', function ($serv, $fd) {
    global $thrift_servers;
    $fdinfo = $serv->connection_info($fd);
    $remote_ip = $fdinfo["remote_ip"];
    $remote_port = $fdinfo["remote_port"];
    $clentKey = $remote_ip.':'.$remote_port;
    unset($thrift_servers[$clentKey]);
    
    echo "Client: Close.<!-\n";
    //var_dump($serv);
    var_dump($fdinfo);
    echo "Client: Close.->\n";
});
echo "ready to start\n";
$serv->start();
echo "start ===";

$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
echo "client start ===";